<?php
class ControllerSaleStockOut extends Controller {
    //出库单列表页
    public function index() {
        $this->load->language('sale/stock_out');
        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('sale/stock_out');
        $this->getList();
    }

    protected function getList() {
        if(isset($this->request->get['filter_refer_id'])){
            $filter_refer_id = $this->request->get['filter_refer_id'];
        }else{
            $filter_refer_id = null;
        }

        if(isset($this->request->get['out_id'])){
            $out_id = $this->request->get['out_id'];
        }else{
            $out_id = null;
        }
        if(isset($this->request->get['filter_name_code'])){
            $filter_name_code = $this->request->get['filter_name_code'];
        }else{
            $filter_name_code = null;
        }
        if(isset($this->request->get['filter_user_name'])){
            $filter_user_name = $this->request->get['filter_user_name'];
        }else{
            $filter_user_name = null;
        }
        if(isset($this->request->get['filter_warehouse'])){
            $filter_warehouse = $this->request->get['filter_warehouse'];
        }else{
            $filter_warehouse = null;
        }
        if(isset($this->request->get['filter_add_date_start'])){
            $filter_add_date_start = $this->request->get['filter_add_date_start'];
        }else{
            $filter_add_date_start = null;
        }
        if(isset($this->request->get['filter_add_date_end'])){
            $filter_add_date_end = $this->request->get['filter_add_date_end'];
        }else{
            $filter_add_date_end = null;
        }
        if(isset($this->request->get['filter_status'])){
            $filter_status = $this->request->get['filter_status'];
        }else{
            $filter_status = null;
        }
        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'so.out_id';
        }
        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }
        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }
        /*
         * 强制添加仓库筛选功能
         * @author sonicsjh
         */
        $data['warehouseLocked'] = 0;
        if ($this->user->getLP() > 0) {
            $data['warehouseLocked'] = $this->user->getLP();
            //$filter_warehouse = $this->user->getLP();//允许看，不允许改
        }

        $url = '';
        if(isset($this->request->get['filter_refer_id'])){
            $url .= '&filter_refer_id=' . $this->request->get['filter_refer_id'];
        }
        if(isset($this->request->get['filter_name_code'])){
            $url .= '&filter_name_code=' . urlencode(html_entity_decode($this->request->get['filter_name_code'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_user_name'])){
            $url .= '&filter_user_name=' . urlencode(html_entity_decode($this->request->get['filter_user_name'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_warehouse'])){
            $url .= '&filter_warehouse=' . $this->request->get['filter_warehouse'];
        }
        if(isset($this->request->get['filter_add_date_start'])){
            $url .= '&filter_add_date_start=' . $this->request->get['filter_add_date_start'];
        }
        if(isset($this->request->get['filter_add_date_end'])){
            $url .= '&filter_add_date_end=' . $this->request->get['filter_add_date_end'];
        }
        if(isset($this->request->get['filter_status'])){
            $url .= '&filter_status=' . $this->request->get['filter_status'];
        }
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }
        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }
        $data['breadcrumbs'] = array();
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
        );
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . $url, 'SSL')
        );
        $data['add'] = $this->url->link('sale/stock_out/add','token=' . $this->session->data['token'] . $url, 'SSL');
        $filter_data = array(
            'out_id'      => $out_id,
            'filter_refer_id'      => $filter_refer_id,
            'filter_name_code'     => $filter_name_code,
            'filter_user_name'     => $filter_user_name,
            'filter_warehouse'     => $filter_warehouse,
            'filter_add_date_start'=> $filter_add_date_start?$filter_add_date_start.' 00:00:00':'',
            'filter_add_date_end'  => $filter_add_date_end?$filter_add_date_end.' 23:59:59':'',
            'filter_status'        => $filter_status,
            'sort'                 => $sort,
            'order'                => $order,
            'start'                => ($page - 1) * $this->config->get('config_limit_admin'),
            'limit'                => $this->config->get('config_limit_admin')
        );
        // var_dump($filter_data);
        $stock_total = $this->model_sale_stock_out->gettotalstockout($filter_data);
        $results = $this->model_sale_stock_out->getstockouts($filter_data);
       

        foreach ($results as $result) {
            //  var_dump(intval($result['logcenter_id']));
            // var_dump($this->user->getLP());
            if (44==$this->user->getId()||3347==$this->user->getId()||intval($result['logcenter_id'] == $this->user->getLP())) {
                $canDeliverAndAccept=1;
            }else{
                $canDeliverAndAccept=0;

            }
            $data['stock_outs'][] = array(
                'out_id'     => $result['out_id'],
                'refer_id'      => $result['refer_id'],
                'refer_type_id' => $result['refer_type_id'],
                'rtname'        => $result['rtname'],
                'warehouse_id' => $result['warehouse_id'],//@author sonicsjh
                'whname'        => $result['whname'],
                'username'      => $result['username'],
                'sale_money' => $result['sale_money'],
                'tsname'      => $result['tsname'],
                'status'     => $result['status'],
                'send_ware_name' => $result['send_ware_name'],
                'canDeliverAndAccept' => $canDeliverAndAccept,
                'cta_day_times' => intval($result['order_auditted_time'])&&intval($result['order_date_added'])?(floor((strtotime($result['order_auditted_time'])-strtotime($result['order_date_added']))/86400)):'',
                'atc_day_times' => intval($result['out_date'])&&intval($result['date_added'])?(floor((strtotime($result['out_date'])-strtotime($result['date_added']))/86400)):'',
                'ctd_day_times' => intval($result['deliver_date'])&&intval($result['out_date'])?(floor((strtotime($result['deliver_date'])-strtotime($result['out_date']))/86400)):'',
                'dtf_day_times' => intval($result['receive_date'])&&intval($result['deliver_date'])?(floor((strtotime($result['receive_date'])-strtotime($result['deliver_date']))/86400)):'',
                'out_date'   => $result['out_date'],
                'deliver_date' => intval($result['deliver_date'])?$result['deliver_date']:'',
                'receive_date' => intval($result['receive_date'])?$result['receive_date']:'',
                'date_added' => $result['date_added'],
                'order_date_added' => $result['order_date_added'],
                'view'       => $this->url->link('sale/stock_out/view', 'token=' . $this->session->data['token'] . '&out_id=' . $result['out_id'], 'SSL'),
                'edit'       => $this->url->link('sale/stock_out/edit', 'token=' . $this->session->data['token'] . '&out_id=' . $result['out_id'], 'SSL')
            );
        }
        $data['heading_title'] = $this->language->get('heading_title');
        $data['text_list'] = $this->language->get('text_list');
        $data['text_no_results'] = $this->language->get('text_no_results');
        $data['text_loading'] = $this->language->get('text_loading');
        $data['text_confirm'] = $this->language->get('text_confirm');
        $data['text_confirm2'] = $this->language->get('text_confirm2');
        $data['text_confirm3'] = $this->language->get('text_confirm3');
        $data['button_view'] = $this->language->get('text_stock_out_detail');
        $data['button_delete'] = $this->language->get('text_stock_out_delete');
        $data['button_recover'] = $this->language->get('text_stock_out_recover');
        $data['button_add'] = $this->language->get('text_stock_out_add');
        $data['button_edit'] = $this->language->get('text_stock_out_edit');
        $data['button_complete'] = $this->language->get('text_stock_out_complete');
        $data['column_out_id'] = $this->language->get('column_out_id');
        $data['column_refer_id'] = $this->language->get('column_refer_id');
        $data['column_refer_type'] = $this->language->get('column_refer_type');
        $data['column_warehouse'] = $this->language->get('column_warehouse');
        $data['column_user'] = $this->language->get('column_user');
        $data['column_money'] = $this->language->get('column_money');
        $data['column_status'] = $this->language->get('column_status');
        $data['column_out_date'] = $this->language->get('column_out_date');
        $data['column_date_added'] = $this->language->get('column_date_added');
        $data['column_action'] = $this->language->get('column_action');
        $data['filter_refer_id'] = $filter_refer_id;
        $data['filter_name_code'] = $filter_name_code;
        $data['filter_user_name'] = $filter_user_name;
        $data['filter_warehouse'] = $filter_warehouse;
        $data['filter_warehouse_array'] = array($filter_warehouse => 'selected');
        $data['filter_add_date_start'] = $filter_add_date_start;
        $data['filter_add_date_end'] = $filter_add_date_end;
        $data['filter_status_array'] = array($filter_status => 'selected');
        $data['filter_status'] = $filter_status;
        $data['token'] = $this->session->data['token'];
        $data['user_id'] = $this->session->data['user_id'];
        if (isset($this->session->data['error'])) {
            $data['error_warning'] = $this->session->data['error'];
            unset($this->session->data['error']);
        } elseif (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }
        $url = '';
        if(isset($this->request->get['filter_refer_id'])){
            $url .= '&filter_refer_id=' . $this->request->get['filter_refer_id'];
        }
        if(isset($this->request->get['filter_name_code'])){
            $url .= '&filter_name_code=' . urlencode(html_entity_decode($this->request->get['filter_name_code'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_user_name'])){
            $url .= '&filter_user_name=' . urlencode(html_entity_decode($this->request->get['filter_user_name'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_warehouse'])){
            $url .= '&filter_warehouse=' . urlencode(html_entity_decode($this->request->get['filter_warehouse'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_add_date_start'])){
            $url .= '&filter_add_date_start=' . $this->request->get['filter_add_date_start'];
        }
        if(isset($this->request->get['filter_add_date_end'])){
            $url .= '&filter_add_date_end=' . $this->request->get['filter_add_date_end'];
        }
        if(isset($this->request->get['filter_status'])){
            $url .= '&filter_status=' . $this->request->get['filter_status'];
        }
        if ($order == 'ASC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }
        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }
        $data['sort_out_id'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.out_id' . $url, 'SSL');
        $data['sort_refer_id'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.refer_id' . $url, 'SSL');
        $data['sort_refer_type'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.refer_type_id' . $url, 'SSL');
        $data['sort_warehouse'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.warehouse_id' . $url, 'SSL');
        $data['sort_user'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.user_id' . $url, 'SSL');
        $data['sort_money'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.sale_money' . $url, 'SSL');
        $data['sort_status'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.status' . $url, 'SSL');
        $data['sort_shipping_zone'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.status' . $url, 'SSL');
        $data['sort_out_date'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.out_date' . $url, 'SSL');
        $data['sort_date_added'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=so.date_added' . $url, 'SSL');
        $data['sort_logcenter_id'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . '&sort=o.logcenter_id' . $url, 'SSL');
        $url = '';
        if(isset($this->request->get['filter_refer_id'])){
            $url .= '&filter_refer_id=' . $this->request->get['filter_refer_id'];
        }
        if(isset($this->request->get['filter_name_code'])){
            $url .= '&filter_name_code=' . urlencode(html_entity_decode($this->request->get['filter_name_code'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_user_name'])){
            $url .= '&filter_user_name=' . urlencode(html_entity_decode($this->request->get['filter_user_name'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_warehouse'])){
            $url .= '&filter_warehouse=' . urlencode(html_entity_decode($this->request->get['filter_warehouse'], ENT_QUOTES, 'UTF-8'));
        }
        if(isset($this->request->get['filter_add_date_start'])){
            $url .= '&filter_add_date_start=' . $this->request->get['filter_add_date_start'];
        }
        if(isset($this->request->get['filter_add_date_end'])){
            $url .= '&filter_add_date_end=' . $this->request->get['filter_add_date_end'];
        }
        if(isset($this->request->get['filter_status'])){
            $url .= '&filter_status=' . $this->request->get['filter_status'];
        }
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }
        $pagination = new Pagination();
        $pagination->total = $stock_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_limit_admin');
        $pagination->url = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
        $data['pagination'] = $pagination->render();
        $data['results'] = sprintf($this->language->get('text_pagination'), ($stock_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($stock_total - $this->config->get('config_limit_admin'))) ? $stock_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $stock_total, ceil($stock_total / $this->config->get('config_limit_admin')));
        $data['sort'] = $sort;
        $data['order'] = $order;
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');
        $data['store'] = HTTPS_CATALOG;
        // API login
        $this->load->model('user/api');
        $api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));
        if ($api_info) {
            $data['api_id'] = $api_info['api_id'];
            $data['api_key'] = $api_info['key'];
            $data['api_ip'] = $this->request->server['REMOTE_ADDR'];
        } else {
            $data['api_id'] = '';
            $data['api_key'] = '';
            $data['api_ip'] = '';
        }
        $data['warehouse_arr'] = $this->model_sale_stock_out->getWarehouse();
        $data['status_arr'] = $this->model_sale_stock_out->getStatus();
        $this->response->setOutput($this->load->view('sale/stock_out_list.tpl', $data));
    }

    public function import(){
        $this->load->model('sale/stock_out');
        $this->model_sale_stock_out->import();
    }

    //出库单详情
    public function view(){
        $this->load->language('sale/stock_out_detail');
        $this->document->setTitle($this->language->get('heading_title'));
        /*
         * 强制添加仓库筛选功能
         * @author sonicsjh
         */
        $data['warehouseLocked'] = 0;
        if ($this->user->getLP() > 0) {
            $data['warehouseLocked'] = $this->user->getLP();
            //$filter_warehouse = $this->user->getLP();//允许看，不允许改
        }
        $this->load->model('sale/stock_out');

        $out_id = $this->request->get['out_id'];
        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            //$sort = 'id';
            $sort = 'order_ids';
        }
        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            //$order = 'DESC';
            $order = 'ASC';
        }
        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }
        $url = '';
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }
        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }
        $data['breadcrumbs'] = array();
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
        );
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('sale/stock_out/view', 'token=' . $this->session->data['token'] . $url, 'SSL')
        );
        $data['return_url'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . $url, 'SSL');
        $data['print_url'] = $this->url->link('sale/stock_out/export', 'token=' . $this->session->data['token'] . $url . '&out_id=' . $out_id , 'SSL');
        $filter_data = array(
            'sort'                 => $sort,
            'order'                => $order,
            'start'                => ($page - 1) * $this->config->get('config_limit_admin'),
            'limit'                => $this->config->get('config_limit_admin')
        );
        $stock_out_info = $this->model_sale_stock_out->getstockoutbyoutid($out_id);
        $results = $this->model_sale_stock_out->getstockdetail($out_id,$filter_data);
        $stock_total = $this->model_sale_stock_out->gettotalstockoutdetail($out_id);
        foreach ($results as $result) {
            $data['stock_out_details'][] = array(
                'product_name' => $result['name'],
                'product_code' => $result['product_code'],
                'sku' => $result['sku'],
                'product_quantity' => $result['product_quantity'],
                'product_price' => $result['product_price'],
                'products_money' => $result['products_money'],
                'order_ids' => ($result['order_ids']%10000)?intval($result['order_ids']/10000).'-'.($result['order_ids']%10000):intval($result['order_ids']/10000),
            );
        }
        //订单级优惠信息
        $data['OTList'] = $this->model_sale_stock_out->getOTList($out_id);
        $historydata = $this->model_sale_stock_out->getstockhistory($out_id);
        $data['histories'] = $historydata;
        $data['out_id'] = $out_id;
        $data['refer_id'] = $stock_out_info['refer_id'];
        $data['refer_type_id'] = $stock_out_info['refer_type_id'];
        $data['refer_type'] = $stock_out_info['rtname'];
        $data['warehouse'] = $stock_out_info['whname'];
        $data['username'] = $stock_out_info['username'];
        $data['sale_money'] = $stock_out_info['sale_money'];
        $data['status'] = $stock_out_info['status'];
        $data['tsname'] = $stock_out_info['tsname'];
        $data['out_date'] = $stock_out_info['out_date'];
        $data['comment'] = $stock_out_info['comment'];
        $data['shipping_fullname'] = $stock_out_info['shipping_fullname'];
        $data['shipping_company'] = $stock_out_info['shipping_company'];
        $data['shipping_address'] = $stock_out_info['shipping_address'];
        $data['shipping_city'] = $stock_out_info['shipping_city'];
        $data['shipping_country'] = $stock_out_info['shipping_country'];
        $data['shipping_zone'] = $stock_out_info['shipping_zone'];
        $data['send_ware_name'] = $stock_out_info['send_ware_name'];
        $data['send_ware_address'] = $stock_out_info['send_ware_address'];
        $data['send_ware_manager'] = $stock_out_info['send_ware_manager'];
        $data['send_ware_contact_tel'] = $stock_out_info['send_ware_contact_tel'];
        $data['heading_title'] = $this->language->get('heading_title');
        $data['text_list'] = $this->language->get('text_list');
        $data['text_no_results'] = $this->language->get('text_no_results');
        $data['text_loading'] = $this->language->get('text_loading');
        $data['column_product_name'] = $this->language->get('column_product_name');
        $data['column_product_code'] = $this->language->get('column_product_code');
        $data['column_product_quantity'] = $this->language->get('column_product_quantity');
        $data['column_product_price'] = $this->language->get('column_product_price');
        $data['column_products_money'] = $this->language->get('column_products_money');
        $data['user_id'] = $this->session->data['user_id'];
        $data['token'] = $this->session->data['token'];
        $data['store'] = HTTPS_CATALOG;
        // API login
        $this->load->model('user/api');
        $api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));
        if ($api_info) {
            $data['api_id'] = $api_info['api_id'];
            $data['api_key'] = $api_info['key'];
            $data['api_ip'] = $this->request->server['REMOTE_ADDR'];
        } else {
            $data['api_id'] = '';
            $data['api_key'] = '';
            $data['api_ip'] = '';
        }
        if (isset($this->session->data['error'])) {
            $data['error_warning'] = $this->session->data['error'];
            unset($this->session->data['error']);
        } elseif (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }
        $url = '';
        if(!empty($out_id)){
            $url .= '&out_id='.$out_id;
        }
        if ($order == 'DESC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }
        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }
        $data['sort_product_name'] = $this->url->link('sale/stock_out/view','token=' . $this->session->data['token'] . '&sort=pd.name' . $url, 'SSL');
        $data['sort_sku'] = $this->url->link('sale/stock_out/view','token=' . $this->session->data['token'] . '&sort=p2.sku' . $url, 'SSL');
        $data['sort_product_code'] = $this->url->link('sale/stock_out/view','token=' . $this->session->data['token'] . '&sort=product_code' . $url, 'SSL');
        $data['sort_product_quantity'] = $this->url->link('sale/stock_out/view','token=' . $this->session->data['token'] . '&sort=product_quantity' . $url, 'SSL');
        $data['sort_product_price'] = $this->url->link('sale/stock_out/view','token=' . $this->session->data['token'] . '&sort=product_price' . $url, 'SSL');
        $data['sort_products_money'] = $this->url->link('sale/stock_out/view','token=' . $this->session->data['token'] . '&sort=products_money' . $url, 'SSL');
        $url = '';
        if(!empty($out_id)){
            $url .= '&out_id='.$out_id;
        }
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }
        $pagination = new Pagination();
        $pagination->total = $stock_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_limit_admin');
        $pagination->url = $this->url->link('sale/stock_out/view', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
        $data['pagination'] = $pagination->render();
        $data['results'] = sprintf($this->language->get('text_pagination'), ($stock_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($stock_total - $this->config->get('config_limit_admin'))) ? $stock_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $stock_total, ceil($stock_total / $this->config->get('config_limit_admin')));
        $data['sort'] = $sort;
        $data['order'] = $order;
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');
        $this->response->setOutput($this->load->view('sale/stock_out_detail_list.tpl', $data));
    }

    public function add(){

        $this->document->addScript('view/javascript/angular.js');
        $this->document->addScript('view/javascript/bhz_ctl.js');
        $this->load->model('sale/stock_out');

        $data['refer_type_arr'] = $this->model_sale_stock_out->getrefertype();
        $data['warehouse_arr'] = $this->model_sale_stock_out->getWarehouse(true);
        $data['status_arr'] = $this->model_sale_stock_out->getStatus();

        if (isset($this->session->data['error'])) {
            $data['error_warning'] = $this->session->data['error'];
            unset($this->session->data['error']);
        } elseif (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

        $data['return_url'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . $url, 'SSL');

        $data['token'] = $this->session->data['token'];

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $this->response->setOutput($this->load->view('sale/stock_out_add.tpl', $data));

    }

    public function edit(){
        $this->load->model('sale/stock_out');
        $this->document->addScript('view/javascript/angular.js');
        $this->document->addScript('view/javascript/bhz_ctl.js');

        $data['refer_type_arr'] = $this->model_sale_stock_out->getrefertype();
        $data['warehouse_arr'] = $this->model_sale_stock_out->getWarehouse();

        if (isset($this->session->data['error'])) {
            $data['error_warning'] = $this->session->data['error'];
            unset($this->session->data['error']);
        } elseif (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

        $data['return_url'] = $this->url->link('sale/stock_out', 'token=' . $this->session->data['token'] . $url, 'SSL');

        $data['token'] = $this->session->data['token'];

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $out_id = $this->request->get['out_id'];
        $data['out_id'] = $out_id;

        $result = $this->model_sale_stock_out->getstockoutbyoutid($out_id);
        $LP = $this->user->getLP();

        if (3347==$this->user->getId()||44==$this->user->getId()) {
            $result['warehouse_id'] = $this->user->getId();

            $LP = $this->user->getId();
        }
        // var_dump($result['warehouse_id']);
        // // var_dump($this->user->getLP());
        // var_dump($LP);die();

        if($result['status'] == 2 || $result['warehouse_id'] != $LP|| 0 == $LP){
            $url = $this->url->link('sale/stock_out/view', 'token=' . $this->session->data['token'] . '&out_id='.$out_id);

            $url = str_replace('&amp;','&',$url);
            
            header("Location: $url");
        }

        $data['refer_id'] = $result['refer_id'];
        $data['warehouse_id'] = array($result['warehouse_id'] => 'selected');
        $data['refer_type'] = array($result['refer_type_id'] => 'selected');
        $data['sale_money'] = $result['sale_money'];
        $data['comment'] = $result['comment'];

        $historydata = $this->model_sale_stock_out->getstockhistory($out_id);

        $data['histories'] = $historydata;

        $this->response->setOutput($this->load->view('sale/stock_out_edit.tpl', $data));
    }

    public function warehouse(){
        $this->load->model('stock/warehouse');
        $json = array();
        $data = json_decode(file_get_contents('php://input'),true);
        $filter_name = $data['filter_name'];
        if(!$filter_name){
          $filter_name='';
        }
        $warehouses = $this->model_stock_warehouse->getWarehouseByName($filter_name);
        if($warehouses){
          $json = $warehouses;
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function getproducts(){
        $this->load->model('sale/stock_out');
        $json = array();
        $data = json_decode(file_get_contents('php://input'),true);
        $filter_code = $data['filter_code'];
        if(!$filter_code){
          $filter_code='';
        }
        $products = $this->model_sale_stock_out->searchProducts($filter_code);

        if($products){
          $json = $products;
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function save(){
        $this->load->model('sale/stock_out');
        $json = array();
        $data = json_decode(file_get_contents('php://input'),true);

        $allowmark = true;

        //验证仓库是否充足
        if(intval($data['status'])){
            foreach($data['products'] as $val){
                $remaindnum = intval($val['num']);
                $available_quantity = intval($this->model_sale_stock_out->getAvailQuanByCodeAndWare($data['warehouse_id'],$val['code']));
                if($remaindnum > $available_quantity){
                    $allowmark = false;
                    break;
                }
            }
        }

        if($allowmark){//库存充足，创建出库单
            $stockoutdata = array(
                'refer_id' => $data['refer_id'],
                'refer_type_id' => $data['refer_type'],
                'warehouse_id' => $data['warehouse_id'],
                'user_id' => $this->session->data['user_id'],
                'sale_money' => 0,//$data['sale_money'],
                'pay_sale_money' => 0,//新增字段
                'status' => $data['status'],
                'comment' => $data['comment']
            );
            $out_id = $this->model_sale_stock_out->add($stockoutdata);
            $historydata = array(
                'out_id' => $out_id,
                'user_id' => $this->session->data['user_id'],
                'comment' => '添加出库单'
            );

            $this->model_sale_stock_out->addstockhistory($historydata);
            $total = 0;
            foreach($data['products'] as $product){
                $stockoutdetaildata = array(
                    'out_id' => $out_id,
                    'product_code' => $product['code'],
                    'product_quantity' => $product['num'],
                    'product_price' => $product['price'],
                    'pay_product_price' => $product['price'],//新增字段
                    'products_money' => $product['total'],
                    'pay_products_money' => $product['total'],//新增字段
                );
                if ($this->model_sale_stock_out->addetail($stockoutdetaildata,$data['warehouse_id'],intval($data['status'])?true:false)) {
                    $total += $product['total'];
                }
            }
            $stockoutdata = array(
                'sale_money' => $total,//$data['sale_money'],
                'pay_sale_money' => $total,//新增字段
            );
            $this->model_sale_stock_out->update($stockoutdata, $out_id);//更新出库单价格

            $json = array('success' => '出库单添加成功');

            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
        }else{
            $json = array('error' => '库存不足');

            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
        }
    }

    //更新出库单
    public function update(){
        $this->load->model('sale/stock_out');
        $json = array();
        $data = json_decode(file_get_contents('php://input'),true);
        $allowmark = true;
        $delete_products = array();
        $status = $this->model_sale_stock_out->getStatusFromStockOut($data['out_id']);
        if(intval($status) == 1 || intval($status) == 0){
            $warehouse_id = $this->model_sale_stock_out->getWareFromStockOut($data['out_id']);
            $stovk_out_detail_result = $this->model_sale_stock_out->getProductinfoFromStockOutDetail($data['out_id']);
            foreach($stovk_out_detail_result as $val){
                $flag = true;
                foreach($data['products'] as $product){
                    if($val['product_code'] == $product['product_code']){
                        $flag = false;
                    }
                }
                if($flag){
                    $delete_products[] = array(
                        'counter_id' => $val['counter_id'],
                        'refer_id' => $val['refer_id'],
                        'product_code' => $val['product_code']
                    );
                    $comment[] = '删除商品:['.$val['pdname'].' ('.$product['product_code'].')]，数量为'.$val['product_quantity'];
                }
            }
            $exist_product = array();
            foreach($data['products'] as $key=>$product){
                if(isset($exist_product[$product['product_code']])){
                    $available_quantity = $exist_product[$product['product_code']];
                }else{
                    $available_quantity = intval($this->model_sale_stock_out->getAvailQuanByCodeAndWare($data['warehouse_id'],$product['product_code']));
                    $exist_product[$product['product_code']] = $available_quantity;
                }
                if(empty($product['id']) || $warehouse_id != $data['warehouse_id']){
                    $remaindnum = intval($product['product_quantity']);
                    if($remaindnum > $available_quantity){
                        $allowmark = false;
                        $json = array('error' => '库存不足');
                        break;
                    }
                    if(isset($exist_product[$product['product_code']])){
                        $exist_product[$product['product_code']] = $exist_product[$product['product_code']] - $remaindnum;
                    }
                    if(empty($product['id'])){
                        $comment[] = '新添加商品:['.$product['name'].' ('.$product['product_code'].')]，数量为'.$product['product_quantity'];
                    }
                }else{
                    $product_quantity = intval($this->model_sale_stock_out->getQuantityFromStockOutDetail($product['id']));
                    $remaindnum = intval($product['product_quantity'] - $product_quantity);
                    $data['products'][$key]['remaindnum'] = $remaindnum;
                    if($remaindnum > $available_quantity){
                        $allowmark = false;
                        $json = array('error' => '库存不足');
                        break;
                    }
                    if(isset($exist_product[$product['product_code']])){
                        $exist_product[$product['product_code']] = $exist_product[$product['product_code']] - $remaindnum;
                    }
                    if($product['product_quantity'] != $product_quantity){
                        $comment[] = '修改商品:['.$product['name'].' ('.$product['product_code'].')]，数量从'.$product_quantity.'修改到'.$product['product_quantity'];
                    }
                }
                if($warehouse_id != $data['warehouse_id']){
                    $warehouse_result = $this->model_sale_stock_out->getWareinfoFromWarehouse($warehouse_id,$data['warehouse_id']);
                    foreach($warehouse_result as $val){
                        if($val['warehouse_id'] == $warehouse_id){
                            $old_warehouse_name = $val['name'];
                        }
                        if($val['warehouse_id'] == $data['warehouse_id']){
                            $new_warehouse_name = $val['name'];
                        }
                    }
                    $comment[] = '仓库从 '.$old_warehouse_name.' 变为 '.$new_warehouse_name;
                }
            }
        }else{
            if(intval($status) == 2 || intval($status) == 3 || intval($status) == 4){
                $allowmark = false;
                $json = array('error' => '完成、派送、签收状态均不得修改');
            }else{
                $allowmark = true;
            }
        }
        if($allowmark){
            $stock_result = $this->model_sale_stock_out->getstockoutbyoutid($data['out_id']);
            $old_warehouse_id = $stock_result['warehouse_id'];
            $stockoutdata = array(
                'refer_id' => $data['refer_id'],
                'warehouse_id' => $data['warehouse_id'],
                'user_id' => $this->session->data['user_id'],
                'sale_money' => $data['sale_money'],
                'pay_sale_money' => $data['sale_money'],
                'comment' => $data['comment']
            );
            $this->model_sale_stock_out->update($stockoutdata,$data['out_id']);
            $historydata = array(
                'out_id' => $data['out_id'],
                'user_id' => $this->session->data['user_id'],
                'comment' => implode('<br>',$comment)
            );
            if(!empty($comment)){
                $this->model_sale_stock_out->addstockhistory($historydata);
            }
            $result = $this->model_sale_stock_out->getstockdetail($data['out_id']);
            foreach($result as $val){
                $mark = true;
                foreach($data['products'] as $product){
                    if($val['id'] == $product['id'])
                        $mark = false;
                }
                if($mark)
                    $this->model_sale_stock_out->deletedetail($val['id'],$old_warehouse_id,intval($status)?true:false);
            }
            foreach($data['products'] as $product){
                if(empty($product['id'])){
                    $insert_data = array(
                        'out_id' => $data['out_id'],
                        'product_code' => $product['product_code'],
                        'product_quantity' => $product['product_quantity'],
                        'product_price' => $product['product_price'],
                        'pay_product_price' => $product['product_price'],
                        'products_money' => $product['products_money'],
                        'pay_products_money' => $product['products_money'],
                    );
                    $this->model_sale_stock_out->addetail($insert_data,$data['warehouse_id'],intval($status)?true:false);
                }else{
                    $update_data = array(
                        'product_code' => $product['product_code'],
                        'product_quantity' => $product['product_quantity'],
                        'product_price' => $product['product_price'],
                        'pay_product_price' => $product['product_price'],
                        'products_money' => $product['products_money'],
                        'pay_products_money' => $product['products_money'],
                        'remaindnum' => $product['remaindnum'],
                    );
                    $this->model_sale_stock_out->updatedetail($update_data,$product['id'],$data['warehouse_id'],$warehouse_id,intval($status)?true:false);
                }
            }
            if((int)$stock_result['refer_type_id'] == 1){
                $products_result = $this->model_sale_stock_out->getStockOutDetailProducts($data['out_id']);
                foreach($products_result as $val){
                    $maxquan = $this->model_sale_stock_out->getSumQuanFromStockOut($val['counter_id'],$val['refer_id'],$val['product_code']);
                    $this->model_sale_stock_out->setOrderProductLackQuan($maxquan,$val['counter_id'],$val['product_code'],$val['refer_id']);
                }
                foreach($delete_products as $val){
                    $maxquan = $this->model_sale_stock_out->getSumQuanFromStockOut($val['counter_id'],$val['refer_id'],$val['product_code']);
                    $this->model_sale_stock_out->setOrderProductLackQuan($maxquan,$val['counter_id'],$val['product_code'],$val['refer_id']);
                }
                //算上出库单中订单级优惠信息，更新出库单总价
                $this->model_sale_stock_out->resetSOTotalWithOTList($data['out_id']);
            }
            $json = array('success' => '出库单修改成功');
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function getdetailproducts(){
        $this->load->model('sale/stock_out');
        $out_id = $this->request->get['out_id'];
        $result = $this->model_sale_stock_out->getstockdetail($out_id);
        foreach($result as $key=>$val){
            $result[$key]['disabled'] = 'true';
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($result));
    }

    //打印出库单详情页
    public function export(){
        $out_id = $this->request->get['out_id'];
        if(!$out_id){
          $out_id = 0;
        }
        $this->load->model('sale/stock_out');
        $export_data = $this->model_sale_stock_out->getexportstock($out_id);
        $OTList = $this->model_sale_stock_out->getOTList($out_id);

        if(!$export_data){
          $this->load->language('error/not_found');
          $this->document->setTitle($this->language->get('heading_title'));
          $data['heading_title'] = $this->language->get('heading_title');
          $data['text_not_found'] = $this->language->get('text_not_found');
          $data['breadcrumbs'] = array();
          $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
          );
          $data['footer'] = $this->load->controller('common/footer');
          $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
        }

        $this->load->library('PHPExcel/PHPExcel');
        $objReader = PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/stock_out_tpl.xls");
        $objPHPExcel->getProperties()
            ->setCreator("Think-tec")
            ->setLastModifiedBy("Think-tec")
            ->setTitle("Bai Huo Zhan SC")
            ->setSubject("Bai Huo Zhan SC")
            ->setDescription("Bai Huo Zhan SC")
            ->setKeywords("Bai Huo Zhan, Think-tec")
            ->setCategory("Think-tec");
        $objActSheet = $objPHPExcel->getActiveSheet();
        $objActSheet->setCellValue('B2', $export_data['shipping_company']);
        $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objActSheet->setCellValue('C2', $export_data['shipping_country'].$export_data['shipping_zone'].$export_data['shipping_city'].$export_data['shipping_address']);
        $objPHPExcel->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objActSheet->setCellValue('B3', $export_data['refer_id']);  
        $objPHPExcel->getActiveSheet()->getStyle('B3')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objActSheet->setCellValue('F3', $out_id);//出库单编号
        $objActSheet->setCellValue('I3', $export_data['customer_id']);  
        $date_added = substr($export_data['date_added'], 0, 10);
        $objActSheet->setCellValue('B4', $date_added);
        $objActSheet->setCellValue('F4', $export_data['payment_method']);
        $objActSheet->setCellValue('F5', (int)$export_data['is_pay']?'已支付':'未支付');
        $objActSheet->setCellValue('I4', $export_data['fullname']);
        $objActSheet->setCellValue('I5', $export_data['payment_fullname']);
        $objActSheet->setCellValue('I6', $export_data['telephone']);
        $row_num = 9;
        $styleBorderOutline = array(
          'borders' => array(
            'outline' => array(
              'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
          ),
        );
        $objPHPExcel->getActiveSheet()->insertNewRowBefore($row_num, count($export_data['product_data']));
        $count = 0;
        $total_price = 0;
        foreach ($export_data['product_data'] as $key => $sc_product) {
          $objActSheet->setCellValue('A'.$row_num, $sc_product['order_ids']);
          $objActSheet->setCellValue('B'.$row_num, $sc_product['product_name']);
          $objActSheet->setCellValue('C'.$row_num, $sc_product['sku']);
          $objActSheet->setCellValue('D'.$row_num, $sc_product['position1']);
          $objActSheet->setCellValue('E'.$row_num, $sc_product['position2']);
          $objActSheet->setCellValue('F'.$row_num, $sc_product['num']);
          $objActSheet->setCellValue('G'.$row_num, $sc_product['price']);
          $objActSheet->setCellValue('H'.$row_num, $sc_product['total']);
          $objActSheet->setCellValue('I'.$row_num, $sc_product['product_code']);

          $count += $sc_product['num'];
          $total_price += $sc_product['total'];

          $objPHPExcel->getActiveSheet()->getStyle('A'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('C'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('D'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('E'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('F'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('G'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('H'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('I'.$row_num)->applyFromArray($styleBorderOutline);
          $objPHPExcel->getActiveSheet()->getStyle('J'.$row_num)->applyFromArray($styleBorderOutline);
          $row_num++;
        }

        $objActSheet->setCellValue('B'.$row_num, '商品小计');
        $objActSheet->setCellValue('F'.$row_num, $count);
        $objActSheet->setCellValue('H'.$row_num, $total_price);
        $row_num++;
        if (count($OTList)) {
            $objPHPExcel->getActiveSheet()->insertNewRowBefore($row_num, count($OTList)+1);
            //显示优惠信息
            foreach ($OTList as $OTInfo) {
                $objActSheet->setCellValue('B'.$row_num, $OTInfo['title']);
                $objActSheet->setCellValue('H'.$row_num, $OTInfo['value']);
                $total_price += $OTInfo['value'];
                $row_num++;
            }
            $objActSheet->setCellValue('B'.$row_num, '出库单小计');
            $objActSheet->setCellValue('H'.$row_num, $total_price);
            $row_num++;
        }
        $objActSheet->setCellValue('B'.$row_num, $export_data['comment']);
        $row_num++;
        $objActSheet->setCellValue('B'.$row_num, '仓库名：'.$export_data['name'].'; 管理员：'.$export_data['manager'].'; 联系电话：'.$export_data['contact_tel'].'; 地址：'.$export_data['address'].';');

        $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objActSheet->setTitle('百货栈商超出库单');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        ob_end_clean();
        // Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="SC_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter->save('php://output'); 
        exit;
    }

    public function add_import(){
        $json = array();
        if (1) {
          if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
            // Sanitize the filename
            $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
            // Validate the filename length
            if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
              $json['error'] = '文件名过短';
            }
            // Allowed file extension types
            $allowed = array('xls','xlsx');
            if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
              $json['error'] = '请上传xls或者xlsx文件';
            }
            // Return any upload error
            if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
              $json['error'] = '上传出现错误';
            }
          } 
        }
        else {
          $json['error'] = '上传失败';
        }

        if (!$json) {
            $this->load->library('PHPExcel/PHPExcel');
              $savePath = $this->request->files['file']['tmp_name'];
              $PHPExcel = new PHPExcel();
            $PHPReader = new PHPExcel_Reader_Excel2007();
            if(!$PHPReader->canRead($savePath)){
              $PHPReader = new PHPExcel_Reader_Excel5();
            }
          $PHPExcel = $PHPReader->load($savePath);

          $objWorksheet = $PHPExcel->getActiveSheet();
          $highestRow = $objWorksheet->getHighestRow(); 

          $code_idx = $num_idx = NULL;
          $tmp_idx = 0;
          $currentRow = 1;
          while(($code_idx === NULL || $num_idx === NULL)&&$tmp_idx<26) {
              switch (trim((String)$objWorksheet->getCellByColumnAndRow($tmp_idx,$currentRow)->getValue())) {
                  case '商品编码':
                      $code_idx = $tmp_idx;
                      break;
                  case '商品数量':
                      $num_idx = $tmp_idx;
                      break;
              }
              $tmp_idx++;
          }

          if(NULL === $code_idx || NULL===$num_idx) {
            $json['error'] = '请检查文件第一行是否有：商品编码、商品数量';
          }
        }

        if (!$json) {
            $this->load->model('sale/stock_out');

            for ($currentRow = 2;$currentRow <= $highestRow;$currentRow++) {
                $product_code = (String)$objWorksheet->getCellByColumnAndRow($code_idx,$currentRow)->getValue();
                $product_num = (String)$objWorksheet->getCellByColumnAndRow($num_idx,$currentRow)->getValue();
                $product_arr = $this->model_sale_stock_out->searchProduct($product_code);
                $product_arr['num'] = $product_num;
                $product_arr['total'] = round(($product_arr['price']*$product_num),2);
                $product_arrs[] = $product_arr;
            }

            $json = array(
                'success' => '导入成功',
                'data' => $product_arrs
            );
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function exportLists(){
        if(isset($this->request->get['filter_refer_id'])){
            $filter_refer_id = $this->request->get['filter_refer_id'];
        }else{
            $filter_refer_id = null;
        }

        if(isset($this->request->get['filter_name_code'])){
            $filter_name_code = $this->request->get['filter_name_code'];
        }else{
            $filter_name_code = null;
        }

        if(isset($this->request->get['filter_user_name'])){
            $filter_user_name = $this->request->get['filter_user_name'];
        }else{
            $filter_user_name = null;
        }

        if(isset($this->request->get['filter_warehouse'])){
            $filter_warehouse = $this->request->get['filter_warehouse'];
        }else{
            $filter_warehouse = null;
        }

        if(isset($this->request->get['filter_add_date_start'])){
            $filter_add_date_start = $this->request->get['filter_add_date_start'];
        }else{
            $filter_add_date_start = null;
        }

        if(isset($this->request->get['filter_add_date_end'])){
            $filter_add_date_end = $this->request->get['filter_add_date_end'];
        }else{
            $filter_add_date_end = null;
        }

        if(isset($this->request->get['filter_status'])){
            $filter_status = $this->request->get['filter_status'];
        }else{
            $filter_status = null;
        }

        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'so.out_id';
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }

        $filter_data = array(
            'filter_refer_id'      => $filter_refer_id,
            'filter_name_code'     => $filter_name_code,
            'filter_user_name'     => $filter_user_name,
            'filter_warehouse'     => $filter_warehouse,
            'filter_add_date_start'=> $filter_add_date_start?$filter_add_date_start.' 00:00:00':'',
            'filter_add_date_end'  => $filter_add_date_end?$filter_add_date_end.' 23:59:59':'',
            'filter_status'        => $filter_status,
            'sort'                 => $sort,
            'order'                => $order,
        );

        $this->load->model('sale/stock_out');

        $results = $this->model_sale_stock_out->getExportStockOuts($filter_data);

        foreach($results as $result){
            $data[] = array(
                'out_id'           => $result['out_id'],
                'order_id'         => $result['order_id'],
                'rtname'           => $result['rtname'],
                'username'         => $result['username'],
                'whname'           => $result['whname'],
                'pdname'           => $result['pdname'],
                'vendor_name'      => $result['vendor_name'],
                'product_code'     => $result['product_code'],
                'sku'              => $result['sku'],
                'model'            => $result['model'],
                'quantity'         => $result['product_quantity'],
                'price'            => $result['product_price'],
                'total'            => $result['products_money'],
                'payment_method'   => $result['payment_method'],
                'is_pay'           => intval($result['is_pay'])?'已支付':'未支付',
                'tsname'           => $result['tsname'],
                'send_ware_name'   => $result['send_ware_name'],
                'shipping_address' => $result['shipping_country'].$result['shipping_zone'].$result['shipping_city'].$result['shipping_address'],
                'cta_day_times'    => intval($result['order_auditted_time'])&&intval($result['order_date_added'])?(floor((strtotime($result['order_auditted_time'])-strtotime($result['order_date_added']))/86400)):'',
                'atc_day_times'    => intval($result['out_date'])&&intval($result['date_added'])?(floor((strtotime($result['out_date'])-strtotime($result['date_added']))/86400)):'',
                'ctd_day_times'    => intval($result['deliver_date'])&&intval($result['out_date'])?(floor((strtotime($result['deliver_date'])-strtotime($result['out_date']))/86400)):'',
                'dtf_day_times'    => intval($result['receive_date'])&&intval($result['deliver_date'])?(floor((strtotime($result['receive_date'])-strtotime($result['deliver_date']))/86400)):'',
                'out_date'         => $result['out_date'],
                'deliver_date'     => intval($result['deliver_date'])?$result['deliver_date']:'',
                'receive_date'     => intval($result['receive_date'])?$result['deliver_date']:'',
                'date_added'       => $result['date_added'],
                'order_date_added' => $result['order_date_added'],
                'comment'          => $result['comment'],
            );
        }

        $this->load->library('PHPExcel/PHPExcel');
        $objPHPExcel = new PHPExcel();    
        $objProps = $objPHPExcel->getProperties();    
        $objProps->setCreator("Think-tec");
        $objProps->setLastModifiedBy("Think-tec");    
        $objProps->setTitle("Think-tec Contact");    
        $objProps->setSubject("Think-tec Contact Data");    
        $objProps->setDescription("Think-tec Contact Data");    
        $objProps->setKeywords("Think-tec Contact");    
        $objProps->setCategory("Think-tec");
        $objPHPExcel->setActiveSheetIndex(0);     
        $objActSheet = $objPHPExcel->getActiveSheet(); 

        $objActSheet->setTitle('Sheet1');
        $col_idx = 'A';

        $headers = array('出库单ID','订单ID','单据类型','操作用户','发货仓库','商品名称','品牌产商','商品编码','条形码','型号','数量','单品价格','单品小计','支付方式','是否付款','出库单状态','收货仓库','配送地址','审核天数','配货天数','干线天数','派送天数','出库时间','派送时间','签收时间','创建时间','订单创建时间','备注');

        $row_keys = array('out_id','order_id','rtname','username','whname','pdname','vendor_name','product_code','sku','model','quantity','price','total','payment_method','is_pay','tsname','send_ware_name','shipping_address','cta_day_times','atc_day_times','ctd_day_times','dtf_day_times','out_date','deliver_date','receive_date','date_added','order_date_added','comment');

        foreach ($headers as $header) {
          $objActSheet->setCellValue($col_idx++.'1', $header);  
        }

        $i = 2;

        foreach ($data as $rlst) {
          $col_idx = 'A';
          foreach ($row_keys as $rk) {
            $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
          }
          $i++;
        }

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        
        ob_end_clean();
        // Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="order_'.date('Y-m-d',time()).'.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter->save('php://output'); 
        exit;
    }

    public function exportCollect(){
        if(isset($this->request->get['filter_refer_id'])){
            $filter_refer_id = $this->request->get['filter_refer_id'];
        }else{
            $filter_refer_id = null;
        }

        if(isset($this->request->get['filter_name_code'])){
            $filter_name_code = $this->request->get['filter_name_code'];
        }else{
            $filter_name_code = null;
        }

        if(isset($this->request->get['filter_user_name'])){
            $filter_user_name = $this->request->get['filter_user_name'];
        }else{
            $filter_user_name = null;
        }

        if(isset($this->request->get['filter_warehouse'])){
            $filter_warehouse = $this->request->get['filter_warehouse'];
        }else{
            $filter_warehouse = null;
        }

        if(isset($this->request->get['filter_add_date_start'])){
            $filter_add_date_start = $this->request->get['filter_add_date_start'];
        }else{
            $filter_add_date_start = null;
        }

        if(isset($this->request->get['filter_add_date_end'])){
            $filter_add_date_end = $this->request->get['filter_add_date_end'];
        }else{
            $filter_add_date_end = null;
        }

        if(isset($this->request->get['filter_status'])){
            $filter_status = $this->request->get['filter_status'];
        }else{
            $filter_status = null;
        }

        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'so.out_id';
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }

        $filter_data = array(
            'filter_refer_id'      => $filter_refer_id,
            'filter_name_code'     => $filter_name_code,
            'filter_user_name'     => $filter_user_name,
            'filter_warehouse'     => $filter_warehouse,
            'filter_add_date_start'=> $filter_add_date_start?$filter_add_date_start.' 00:00:00':'',
            'filter_add_date_end'  => $filter_add_date_end?$filter_add_date_end.' 23:59:59':'',
            'filter_status'        => $filter_status,
            'sort'                 => $sort,
            'order'                => $order,
        );

        $this->load->model('sale/stock_out');

        $results = $this->model_sale_stock_out->getstockouts($filter_data);

        foreach($results as $result){
            $save_data[] = array(
                'out_id' => $result['out_id'],
                'order_id' => $result['refer_id'],
                'rtname' => $result['rtname'],
                'username' => $result['username'],
                'whname' => $result['whname'],
                'total' => $result['sale_money'],
                'payment_method' => $result['payment_method'],
                'is_pay' => intval($result['is_pay'])?'已支付':'未支付',
                'tsname' => $result['tsname'],
                'send_ware_name' => $result['send_ware_name'],
                'shipping_address' => $result['shipping_country'].$result['shipping_zone'].$result['shipping_city'].$result['shipping_address'],
                'cta_day_times'    => intval($result['order_auditted_time'])&&intval($result['order_date_added'])?(floor((strtotime($result['order_auditted_time'])-strtotime($result['order_date_added']))/86400)):'',
                'atc_day_times'    => intval($result['out_date'])&&intval($result['date_added'])?(floor((strtotime($result['out_date'])-strtotime($result['date_added']))/86400)):'',
                'ctd_day_times'    => intval($result['deliver_date'])&&intval($result['out_date'])?(floor((strtotime($result['deliver_date'])-strtotime($result['out_date']))/86400)):'',
                'dtf_day_times'    => intval($result['receive_date'])&&intval($result['deliver_date'])?(floor((strtotime($result['receive_date'])-strtotime($result['deliver_date']))/86400)):'',
                'out_date' => $result['out_date'],
                'deliver_date'     => intval($result['deliver_date'])?$result['deliver_date']:'',
                'receive_date'     => intval($result['receive_date'])?$result['deliver_date']:'',
                'date_added' => $result['date_added'],
                'order_date_added' => $result['order_date_added'],
                'comment' => $result['comment'],
            );
        }

        $headers = array('出库单ID','订单ID','单据类型','操作用户','发货仓库','总价','支付方式','是否付款','出库单状态','收货仓库','配送地址','审核天数','配货天数','干线天数','派送天数','出库时间','派送时间','签收时间','创建时间','订单创建时间','备注');
        $row_keys = array('out_id','order_id','rtname','username','whname','total','payment_method','is_pay','tsname','send_ware_name','shipping_address','cta_day_times','atc_day_times','ctd_day_times','dtf_day_times','out_date','deliver_date','receive_date','date_added','order_date_added','comment');

        $this->load->helper('export');
        prepareDownloadExcel($save_data, $headers, $row_keys, 'Stock_outs');
    }
}